package com.example.thornchg.yc_plane_game.enemy;

import com.example.thornchg.yc_plane_game.Hero;

import org.cocos2d.actions.instant.CCHide;
import org.cocos2d.actions.interval.CCAnimate;
import org.cocos2d.actions.interval.CCSequence;
import org.cocos2d.nodes.CCAnimation;
import org.cocos2d.nodes.CCDirector;
import org.cocos2d.nodes.CCSprite;
import org.cocos2d.nodes.CCSpriteFrame;
import org.cocos2d.sound.SoundEngine;
import org.cocos2d.types.CGSize;

import java.util.ArrayList;
import java.util.Locale;

public abstract class Enemy extends CCSprite {
    private boolean isDead;
    private String filePath;
    private int score;
    public CGSize winSize;
    private int maxHP;
    private int currentHP;
    private ArrayList<CCSpriteFrame> deadFrames;
    public Enemy(String filepath,int maxHP,int deadFramesCount,String deadFramesFormat) {
        super(filepath);
        setAnchorPoint(0.5f, 0);
        this.filePath=filepath;
        this.isDead=false;
        this.maxHP=maxHP;
        this.currentHP=this.maxHP;
        this.score=100;
        this.winSize=CCDirector.sharedDirector().getWinSize();
        deadFrames=new ArrayList<>();
        for (int i = 0; i < deadFramesCount; i++) {
            CCSpriteFrame ccSpriteFrame=CCSprite.spriteWithSpriteFrameName(String.format(Locale.CHINA,
                    deadFramesFormat,
                    i+1)).displayedFrame();
            deadFrames.add(ccSpriteFrame);
        }
    }

    public boolean isDead() {
        return isDead;
    }

    public void beAttacked(Hero hero){
        currentHP-=hero.getAttackPower();
        showBeAttacked();
        if (currentHP<=0) {
            dead();
        }
    }

    public void showBeAttacked(){}


    private void dead(){
        playDeadEffect();
        this.isDead=true;
        stopAllActions();
        showExplosion();
    }
    private void showExplosion(){
        CCAnimation ccAnimation=CCAnimation.animationWithFrames(deadFrames,.1f);
        CCAnimate ccAnimate=CCAnimate.action(ccAnimation,false);
        CCHide ccHide=CCHide.action();
        CCSequence ccSequence=CCSequence.actions(ccAnimate,ccHide);
        runAction(ccSequence);
    }

    public void setIsDead(boolean isDead) {
        this.isDead=isDead;
    }
    public void resume(){
        this.currentHP=this.maxHP;
        setVisible(true);
        setIsDead(false);
        setDisplayFrame(CCSprite.spriteWithSpriteFrameName(filePath)
                .displayedFrame());
        setStartPosition();
        move();
    }

    public int getScore() {
        return score;
    }

    public void setScore(int score) {
        this.score = score;
    }
    public abstract void playDeadEffect();
    public abstract void move();
    public abstract void setStartPosition();
}
